/* ************************************************************************
> File Name:     8.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月06日 星期五 18时03分15秒
> Description:   
 ************************************************************************/
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
#include"inthash.h"
#define ARRSIZE 1000000
#define SIZE 2000000

void get_arr(int **a, size_t s);
size_t intersect(const int a[], size_t nmema, const int b[], size_t nmemb, int c[], size_t nmemc);
int func(int x);
int in_arr(int x, int key, int arr[]);

int main(void)
{
    int *a;
    int *b;
    int *c;

    get_arr(&a, ARRSIZE);
    get_arr(&b, ARRSIZE);
    c = malloc(SIZE * sizeof(int));
    
    int k = intersect(a, ARRSIZE, b, ARRSIZE, c, SIZE);

    int i;
    for (i = 0; i < ARRSIZE; ++i){
        printf("%d\n", a[i]);
    }
    puts("-----------");

    for (i = 0; i < ARRSIZE; ++i){
        printf("%d\n", b[i]);
    }
    puts("-----------");

    for (i = 0; i < k; ++i){
        printf("%d\n", c[i]);
    }

    return 0;
}

void get_arr(int **a, size_t s)
{
    *a = malloc(s * sizeof(int));
    //srand(time(NULL));

    int i = 0;
    while (i != s){
        int tmp = rand();
        if (!in_arr(tmp, i, *a)){
            (*a)[i] = tmp;
            ++i;
        }
    }
}

size_t intersect(const int a[], size_t nmema, const int b[], size_t nmemb, int c[], size_t nmemc)
{
    my_hash h = {NULL, nmema + nmemb, func, NULL, 0};
    int i;
    for (i = 0; i < nmema; ++i){
        insert(&h, a[i]);
    }

    for (i = 0; i < nmemb; ++i){
        insert(&h, b[i]);
    }

    int k = 0;
    for (i = 0; i < nmema + nmemb; ++i){
        intlist tmp = {(h.p)[i]};
        if (get_list_size(&tmp) > 1){
            if (k < nmemc){
                c[k] = tmp.head->item;
                ++k;
            }
            else{
                break;
            }
        }
    }

    return k;
}

int func(int x)
{
    return x;
}

int in_arr(int x, int key, int arr[])
{
    int i;
    for (i = 0; i < key; ++i){
        if (x == arr[i]){
            return 1;
        }
    }

    return 0;
}
